{% extends "admin/base.html" %}

{% block title %}标签管理{% endblock %}

{% block content %}
<div class="tags-container">
    <!-- 页面头部 -->
    <div class="tags-header">
        <h1><i class="fas fa-tags"></i> 标签管理</h1>
        <div class="tags-actions">
            <button class="btn-primary" onclick="showAddTagModal()">
                <i class="fas fa-plus"></i>
                新建标签
            </button>
        </div>
    </div>
    
    <!-- 筛选和搜索区域 -->
    <div class="tags-filters">
        <div class="filter-group">
            <label for="search-input">搜索标签</label>
            <input type="text" id="search-input" placeholder="输入标签名称或描述关键词...">
        </div>
        
        <button class="btn-filter" onclick="applyFilters()">
            <i class="fas fa-search"></i>
            搜索
        </button>
        
        <button class="btn-reset" onclick="resetFilters()">
            <i class="fas fa-undo"></i>
            重置
        </button>
    </div>
    
    <!-- 标签列表 -->
    <div class="table-responsive">
        <table class="tags-table">
            <thead>
                <tr>
                    <th style="width: 35%;">标签名称</th>
                    <th style="width: 40%;">描述</th>
                    <th style="width: 15%;">创建时间</th>
                    <th style="width: 10%;">操作</th>
                </tr>
            </thead>
            <tbody id="tags-tbody"></tbody>
        </table>
    </div>
    
    <!-- 模态框：新建/编辑标签 -->
    <div id="tag-modal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="tag-modal-title">新建标签</h2>
                <button class="modal-close" onclick="hideTagModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="tag-form">
                    <input type="hidden" id="tag-id" name="id">
                    <div class="form-group">
                        <label for="tag-name">标签名称 *</label>
                        <input type="text" id="tag-name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="tag-description">描述</label>
                        <textarea id="tag-description" name="description" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="hideTagModal()">取消</button>
                <button type="button" class="btn-primary" onclick="saveTag()">保存</button>
            </div>
        </div>
    </div>

</div>

<!-- 分页 -->
<div class="mt-0">
    <div class="bg-white rounded-b-lg shadow-md p-6">
        <div class="flex items-center justify-between">
            <!-- 分页信息 -->
            <div class="text-sm text-gray-600" id="pagination-info">暂无记录</div>
            
            <!-- 分页导航 -->
            <nav class="flex items-center space-x-1" id="pagination-nav"></nav>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
/* 容器，与文章/分类保持一致，上圆角、下直角 */
.tags-container {
    background: #fff;
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;
    border-bottom-left-radius: 0;
    border-bottom-right-radius: 0;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    overflow: hidden;
    margin: 0;
}

.tags-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.tags-header h1 { margin: 0; color: #2c3e50; font-size: 1.25rem; font-weight: 600; }

.tags-actions { display: flex; gap: 1rem; align-items: center; }

.btn-primary { background: #007bff; color: #fff; padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 500; font-size: 0.875rem; transition: all .3s ease; display: inline-flex; align-items: center; gap: .5rem; cursor: pointer; }
.btn-primary:hover { background: #0056b3; color: #fff; }

.tags-filters { padding: 1.5rem 2rem; background: #f8f9fa; border-bottom: 1px solid #e1e8ed; display: flex; gap: 1rem; align-items: center; flex-wrap: wrap; }
.filter-group { display: flex; flex-direction: column; gap: .5rem; }
.filter-group label { font-size: .875rem; font-weight: 500; color: #495057; }
.filter-group input { padding: .5rem; border: 1px solid #ced4da; border-radius: 6px; font-size: .875rem; min-width: 200px; }
.btn-filter { background: #007bff; color: #fff; border: none; padding: .5rem 1rem; border-radius: 6px; cursor: pointer; font-size: .875rem; transition: background .3s ease; align-self: flex-end; }
.btn-filter:hover { background: #0056b3; }

.btn-reset {
    background: #6c757d;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.875rem;
    transition: background 0.3s ease;
    align-self: flex-end;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-reset:hover {
    background: #5a6268;
}

.table-responsive { overflow-x: auto; }
.tags-table { width: 100%; border-collapse: collapse; }
.tags-table th { background: #f8f9fa; padding: 1rem; text-align: left; font-weight: 600; color: #495057; border-bottom: 2px solid #dee2e6; font-size: .875rem; }
.tags-table td { padding: 1rem; border-bottom: 1px solid #f1f3f4; vertical-align: middle; }
.tags-table tbody tr:hover { background: #f8f9fa; }

.tag-name { margin: 0 0 .25rem 0; font-size: 1rem; font-weight: 600; color: #333; }
.tag-description { font-size: .875rem; color: #666; line-height: 1.4; max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tag-date { font-size: .875rem; color: #666; }
.tag-actions { display: flex; gap: .5rem; }
.btn-action { padding: 0.375rem 0.75rem; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease; font-size: 0.875rem; text-decoration: none; display: inline-flex; align-items: center; justify-content: center; }
.btn-edit { background: #007bff; color: white; }
.btn-edit:hover { background: #0056b3; color: white; text-decoration: none; }
.btn-delete { background: #dc3545; color: white; }
.btn-delete:hover { background: #c82333; color: white; }

.empty-state { text-align: center; padding: 3rem 1rem; color: #6c757d; }
.empty-state i { font-size: 2rem; margin-bottom: .5rem; }
.empty-state h3 { margin: .25rem 0; color: #2c3e50; }
.empty-state p { margin: 0; }

/* 复用分类页的模态样式 */
.modal-overlay { position: fixed; inset: 0; background-color: rgba(0,0,0,.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal-content { background: #fff; border-radius: 8px; box-shadow: 0 10px 25px rgba(0,0,0,.2); width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto; }
.modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem 2rem; border-bottom: 1px solid #e9ecef; }
.modal-header h2 { margin: 0; font-size: 1.25rem; color: #333; }
.modal-close { background: none; border: none; font-size: 1.25rem; color: #666; cursor: pointer; padding: .5rem; border-radius: 4px; }
.modal-close:hover { background-color: #f8f9fa; }
.modal-body { padding: 2rem; }
.modal-footer { display: flex; justify-content: flex-end; gap: 1rem; padding: 1.5rem 2rem; border-top: 1px solid #e9ecef; }
.form-group { margin-bottom: 1.5rem; }
.form-group label { display: block; margin-bottom: .5rem; font-weight: 500; color: #333; }
.form-group input, .form-group textarea, .form-group select { width: 100%; padding: .75rem; border: 1px solid #ddd; border-radius: 4px; font-size: .875rem; }
.btn-secondary { background-color: #6c757d; color: #fff; }
.btn-secondary:hover { background-color: #545b62; }
</style>
{% endblock %}

{% block extra_js %}
<script>
// 标签管理数据
let allTags = [];
let filteredTags = [];
let currentPage = 1;
const perPage = 10;

function formatDate(iso) {
    if (!iso) return '';
    try { return iso.slice(0, 10); } catch { return ''; }
}

async function fetchTags() {
    const res = await fetch('/api/tags');
    const json = await res.json();
    if (!json.success) throw new Error('加载标签失败');
    allTags = json.data || [];
}

function applyFilters() {
    const keyword = (document.getElementById('search-input').value || '').trim().toLowerCase();
    filteredTags = allTags.filter(tag => {
        const name = (tag.name || '').toLowerCase();
        const desc = (tag.description || '').toLowerCase();
        return name.includes(keyword) || desc.includes(keyword);
    });
    currentPage = 1;
    renderTable();
    renderPagination();
}

function resetFilters() {
    document.getElementById('search-input').value = '';
    applyFilters();
}

// 模态框
function showAddTagModal() {
    document.getElementById('tag-modal-title').textContent = '新建标签';
    document.getElementById('tag-form').reset();
    document.getElementById('tag-id').value = '';
    document.getElementById('tag-modal').style.display = 'flex';
}
function editTag(id) {
    const tag = allTags.find(t => t.id === id);
    if (!tag) { Utils.notification.show('标签不存在', 'error'); return; }
    document.getElementById('tag-modal-title').textContent = '编辑标签';
    document.getElementById('tag-id').value = String(id);
    document.getElementById('tag-name').value = tag.name || '';
    document.getElementById('tag-description').value = tag.description || '';
    document.getElementById('tag-modal').style.display = 'flex';
}
function deleteTag(id) {
    Utils.confirm.show(`确定要删除该标签吗？此操作不可恢复。`, async () => {
        try {
            const res = await fetch(`/api/tags/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } });
            const json = await res.json();
            if (json.success) {
                Utils.notification.show('删除成功', 'success');
                await refreshData();
            } else {
                Utils.notification.show(json.message || '删除失败', 'error');
            }
        } catch (e) {
            Utils.notification.show('删除失败，请稍后重试', 'error');
        }
    });
}

function hideTagModal() {
    document.getElementById('tag-modal').style.display = 'none';
}

async function saveTag() {
    const fd = new FormData(document.getElementById('tag-form'));
    const id = fd.get('id');
    const name = (fd.get('name') || '').trim();
    if (!name) { Utils.notification.show('请输入标签名称', 'error'); return; }
    const payload = {
        name,
        description: fd.get('description') || ''
    };
    const isEdit = !!id;
    try {
        const res = await fetch(isEdit ? `/api/tags/${id}` : '/api/tags', {
            method: isEdit ? 'PUT' : 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const json = await res.json();
        if (json.success) {
            Utils.notification.show(isEdit ? '更新成功' : '创建成功', 'success');
            hideTagModal();
            await refreshData();
        } else {
            Utils.notification.show(json.message || '保存失败', 'error');
        }
    } catch (e) {
        Utils.notification.show('保存失败，请稍后重试', 'error');
    }
}

function renderTable() {
    const tbody = document.getElementById('tags-tbody');
    tbody.innerHTML = '';
    const start = (currentPage - 1) * perPage;
    const pageItems = filteredTags.slice(start, start + perPage);
    if (pageItems.length === 0) {
        const tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="4" class="empty-state">
            <i class="fas fa-tags"></i>
            <h3>暂无标签</h3>
            <p>开始创建你的第一个标签吧！</p>
            <button class="btn-primary" onclick="showAddTagModal()" style="margin-top: 1rem;">
                <i class="fas fa-plus"></i>
                新建标签
            </button>
        </td>`;
        tbody.appendChild(tr);
        return;
    }
    for (const tag of pageItems) {
        const tr = document.createElement('tr');
        tr.setAttribute('data-tag-id', tag.id);
        tr.innerHTML = `
            <td>
                <div class="tag-info">
                    <h3 class="tag-name">${tag.name}</h3>
                </div>
            </td>
            <td>
                <div class="tag-description">${tag.description || '暂无描述'}</div>
            </td>
            <td>
                <span class="tag-date">${formatDate(tag.created_at)}</span>
            </td>
            <td>
                <div class="tag-actions">
                    <button class="btn-action btn-edit" onclick="editTag(${tag.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-action btn-delete" onclick="deleteTag(${tag.id})" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>`;
        tbody.appendChild(tr);
    }
}

function renderPagination() {
    const info = document.getElementById('pagination-info');
    const nav = document.getElementById('pagination-nav');
    nav.innerHTML = '';
    const total = filteredTags.length;
    if (total === 0) { info.textContent = '暂无记录'; return; }
    const start = (currentPage - 1) * perPage + 1;
    const end = Math.min(currentPage * perPage, total);
    info.textContent = `显示第 ${start} - ${end} 条，共 ${total} 条记录`;
    const pages = Math.ceil(total / perPage);
    const mkBtn = (html, disabled, onClick) => {
        const el = document.createElement(disabled ? 'span' : 'a');
        el.className = disabled ? 'px-3 py-2 text-gray-300 cursor-not-allowed' : 'px-3 py-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
        el.innerHTML = html;
        if (!disabled) el.addEventListener('click', onClick);
        return el;
    };
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-left"></i>', currentPage === 1, () => { currentPage = 1; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-chevron-left"></i>', currentPage === 1, () => { currentPage--; renderTable(); renderPagination(); }));
    for (let p = 1; p <= pages; p++) {
        if (p === currentPage) {
            const span = document.createElement('span');
            span.className = 'px-3 py-2 bg-blue-600 text-white rounded-lg font-medium';
            span.textContent = String(p);
            nav.appendChild(span);
        } else {
            const a = document.createElement('a');
            a.className = 'px-3 py-2 text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors';
            a.textContent = String(p);
            a.addEventListener('click', () => { currentPage = p; renderTable(); renderPagination(); });
            nav.appendChild(a);
        }
    }
    nav.appendChild(mkBtn('<i class="fas fa-chevron-right"></i>', currentPage === pages, () => { currentPage++; renderTable(); renderPagination(); }));
    nav.appendChild(mkBtn('<i class="fas fa-angle-double-right"></i>', currentPage === pages, () => { currentPage = pages; renderTable(); renderPagination(); }));
}

async function refreshData() {
    await fetchTags();
    applyFilters();
}

document.addEventListener('DOMContentLoaded', async () => {
    try { await refreshData(); } catch (e) { Utils.notification.show('标签加载失败', 'error'); }
});
</script>
{% endblock %}


